<script setup lang='ts' name="app-management">
import { getCardList, getCompanyByLoginUser, getCompanyCard, getUserInfo, openCard } from '@fl/api/joint-api'
import { useUserStoreWithOut } from '@fl/store/modules/user'
import { useSessionStorage } from '@vueuse/core'
import { ElButton, ElCard } from 'element-plus'
import { cloneDeep } from 'lodash-es'
import { ref } from 'vue'
import { Calendar, Search } from '@element-plus/icons-vue'
import { usePermissionStoreWithOut } from '@/store/modules/permission'
import { cookieClear } from '@fl/logics/authentication'
// 所有卡片
const list = ref<any>([])
// 公司已分配卡片
const companyHasCardList = ref<any>([])
const loading = ref(true)
const search = ref('')

const statusEnum = {
    0: '未开通',
    1: '已开通',
}
const userStore = useUserStoreWithOut()
const userInfo = userStore.getUserInfo

async function getList() {
    loading.value = true
    try {
        if (['2', '3'].includes(userInfo.userStep)) {
            // 获取本企业已开通的卡片
            const companyDetail = await getCompanyByLoginUser()
            // window.sessionStorage.setItem('companyId', companyDetail.id)
            useSessionStorage('companyId', companyDetail.id)
            useSessionStorage('companyDetail', companyDetail)
            console.log('🚀 ~ getCompanyCard ~ res:', companyDetail)
            companyHasCardList.value = companyDetail?.companyCardAssociationList || []
        }
        const cardList = await getCardList()
        console.log('🚀 ~ getCardList ~ cardList:', cardList)
        const res = cloneDeep(cardList)
        // 处理卡片数据
        res.list.forEach((item) => {
            const hasCard = companyHasCardList.value.find((card) => {
                if (Number(card.cardId) === item.id)
                    return card
            })
            console.log('🚀 ~ res.list.forEach ~ hasCard:', hasCard)

            if (hasCard) {
                item.openFlag = hasCard.openFlag
                item.disabled = false
            }
            else {
                item.openFlag = false
                item.disabled = true
            }
        })

        // 筛选掉联合运营
        list.value = res?.list.filter(item => !item.name.includes('联合运营')) || []
        console.log('🚀 ~ getList ~ list.value:', list.value)
        loading.value = false
    }
    catch (error) {
        console.error('🚀 ~ getList ~ error:', error)
        loading.value = false
    }
}

onMounted(() => {
    getList()
})

const visible = ref(false)

function open(id) {
    console.log(id)
    openCard(id).then((res) => {
        console.log('🚀 ~ openCard ~ res:', res)
        if (res) {
            visible.value = true
            ElMessage.success('开通成功')
            getList()
        }
        else {
            ElMessage.error(res.message || '开通失败')
        }
    }).catch((err) => {
        console.error('🚀 ~ openCard ~ err:', err)
        ElMessage.error(err.message || '开通失败')
    })
}



const { mutateAsync: runGetUserInfo } = useMutation({
    mutationFn: () => getUserInfo(),
    mutationKey: ['getUserInfo'],
    onSuccess: async (res) => {
        visible.value = false
        window.location.reload()
    },
    onError: (error) => {
        console.error('获取失败', error)
    },
})

function reload() {
    runGetUserInfo()
}

function reLogin() {
    window.localStorage.clear()
    window.sessionStorage.clear()
    cookieClear()
    userStore.reset()
    window.location.reload()
}
</script>

<template>
    <div class="app-management">
        <div class="title mb-40">
            <div class="mb-8 font-size-20 font-600">
                应用管理
            </div>

            <!-- <ElButton type="primary"
                      @click="reload"
            >
                刷新
            </ElButton>

            <ElButton type="primary"
                      @click="reLogin"
            >
                重新登录
            </ElButton> -->

            <!-- <div class="search mb-40 ml[auto] h-32 w-240">
                <el-input v-model="search"
                          class="inline-block w-300"
                          placeholder="搜索服务"
                          :suffix-icon="Search"
                />
            </div> -->
        </div>

        <div v-loading="loading"
             class="app-management flex flex-wrap gap-20 h-full w-full content-start"
        >
            <ElCard v-for="item in list"
                    v-if="list.length"
                    :key="item.appCode"
                    :label="item.appName"
                    shadow="hover"
                    :class="item.disabled ? 'important-filter-grayscale shadow-none shrink-0 basis-360 flex-wrap h-240 ' : 'shadow-none shrink-0 basis-360 flex-wrap h-240'"
            >
                <div class="app-card">
                    <div class="flex h-200">
                        <el-icon class="app-card-icon mr-8 mt-4"
                                 size="20"
                        >
                            <Management color="#409eff" />
                        </el-icon>

                        <div class="flex flex-col h-[100%] w-[100%] justify-between items-center">
                            <div class="self-start">
                                <div class="app-card-name mb-10 font-size-18 font-600 flex items-center">
                                    <span class="mr-10">{{ item.name }}</span>

                                    <el-tag v-if="item.openFlag === '1'"
                                            class="app-card-tag"
                                            type="success"
                                    >
                                        <div class="flex items-center">
                                            <el-icon>
                                                <SuccessFilled />
                                            </el-icon>

                                            {{ statusEnum[item.openFlag] }}
                                        </div>
                                    </el-tag>
                                </div>

                                <div class="color-gray text-ellipsis h-108 overflow-hidden">
                                    {{ item.description }}
                                </div>
                            </div>

                            <div v-if="item.disabled"
                                 class="color-gray line-height-32 text-right w-240"
                            >
                                服务未开通
                            </div>

                            <ElButton v-if="!item.disabled && item.openFlag === '0'"
                                      plain
                                      type="primary"
                                      class="self-end"
                                      color="#409eff"
                                      @click="open(item.id)"
                            >
                                开通应用
                            </ElButton>
                        </div>
                    </div>
                </div>
            </ElCard>

            <ElCard v-else
                    class="shadow-none shrink-0 basis-300 flex-wrap h-240"
            >
                <div class="app-card">
                    <div class="flex flex-col h-200">
                        <div>
                            <el-icon class="app-card-icon mr-8 mt-4"
                                     size="24"
                            >
                                <Management color="#409eff" />
                            </el-icon>
                        </div>

                        <div class="text-center flex flex-col h-120 justify-center items-center">
                            <span class="mr-10">暂无数据</span>
                        </div>
                    </div>
                </div>
            </ElCard>

            <el-dialog v-model="visible"
                       width="666px"
            >
                <el-icon><SuccessFilled color="#67c23a" /></el-icon>

                <span>开通成功</span>

                <template #footer>
                    <div class="dialog-footer">
                        <ElButton @click="visible = false">
                            关闭并继续开通其他应用服务
                        </ElButton>

                        <ElButton type="primary"
                                  @click="reload"
                        >
                            刷新页面，继续创建用户等
                        </ElButton>

                        <!-- <ElButton type="primary"
                                  @click="reLogin"
                        >
                            退出重新登录，继续创建用户等
                        </ElButton> -->
                    </div>
                </template>
            </el-dialog>
        </div>
    </div>
</template>

<style lang="scss" scoped>
.demo-tabs > .el-tabs__content {
    padding: 32px;
    color: #6b778c;
    font-size: 32px;
    font-weight: 600;
}
.text-ellipsis {
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 5; /* 控制行数 */
    -webkit-box-orient: vertical;
}
</style>
